import { draw, winuser } from 'easywin'
import { remote } from 'electron'

const _aside = document.querySelector("#aside > ul")
const container = document.querySelector("#container")
let pickWinStart = false
globalThis.shortcut = new Proxy({
  win_pickWin: ''
}, {
  set(t, p, v, r) {
    if (p === 'win_pickWin') {
      //窗口拾取快捷键
      if (t[p] !== '') {
        remote.globalShortcut.unregister(t[p])
      }
      remote.globalShortcut.register(v, () => {

        if (globalThis.VWA) {
          if (pickWinStart == false) {
            let { ptScreenPos: p } = winuser.GetCursorInfo()
            let hwnd = winuser.WindowFromPoint(p.x, p.y)
            pickWinStart = true
            draw.drawBorder(hwnd, { flash: true })
            //因为绘制边框闪动有60ms的延迟
            //所有这里设置个时间锁62ms来进行绘制,JS延时会有偏差,这里加了2ms.
            setTimeout(() => {
              pickWinStart = false
            }, 62);
            globalThis.VWA.render(hwnd)
          }
        }

      })
    }
    return Reflect.set(t, p, v, r)
  }
})
globalThis.shortcut.win_pickWin = 'F2'
//将整个窗口的属性放置在globalthis.manager用于管理及响应式
globalThis.manager = new Proxy({
  index: 0,
  focus: 0,//不想破坏html，手动实现下焦点方便键盘事件。aside:1,main:2
  aside: new Proxy({
    index: undefined,
    len: _aside.childElementCount,
    el: _aside,
    childs: _aside.children
  }, {
    set(t, p, v, r) {
      if (p = 'index') {
        if (t[p] == v) {
          return false
        }
        globalThis.manager.index = v
      }
      return Reflect.set(t, p, v, r)
    }
  }),
  events: {

  }
}, {
  set(t, p, v, r) {
    if (p === 'index') {
      //移除当前节点及对应侧边栏选项
      let rmId = t[p]
      if (globalThis.manager.events[rmId] && globalThis.manager.events[rmId].beforeRemove) {
        globalThis.manager.events[rmId].beforeRemove()
      }
      _aside.children[t[p]].classList.remove('index')
      container.removeChild(container.firstElementChild)

      //将切换视图的模板载入
      _aside.children[v].classList.add('index')
      container.appendChild(document.importNode(
        (document.querySelector(`#${_aside.children[v].getAttribute('data-temp')}`) as HTMLTemplateElement).content,
        true
      ))
      //对应视图show事件触发节点
      if (globalThis.manager.events[v] && globalThis.manager.events[v].show) {
        globalThis.manager.events[v].show()
      }
    }
    return Reflect.set(t, p, v, r)
  }
})


//#region 自定焦点变更 
document.body.addEventListener('click', e => {
  globalThis.manager.focus = 0

  let path = e.path
  for (let index = 0; index < path.length; index++) {
    const element = path[index];
    if (element.id === 'aside') {
      globalThis.manager.focus = 1
      break;
    }
    if (element.id === 'container') {
      globalThis.manager.focus = 2
      break;
    }
  }
})
//#endregion


